package com.xinfu.newproject.model.up_iamge;

import android.annotation.SuppressLint;

import com.xinfu.newproject.apiservice.JsNetworkService;
import com.xinfu.newproject.bean.up_image.UpImageBean;
import com.xinfu.newproject.bean.up_image.UpImageBody;
import com.xinfu.newproject.callback.MyCallBack;
import com.xinfu.newproject.model.IModel;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import id.zelory.compressor.Compressor;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class UpImageModel implements IModel.IUpImageModel {

    private List<MultipartBody.Part> list;

    @SuppressLint("CheckResult")
    @Override
    public void upImage(UpImageBody upImageBody, MyCallBack<UpImageBean> callBack) {
        list = new ArrayList<>();
        for (int i = 0; i < upImageBody.getImageList().size(); i++) {
            if (!upImageBody.getImageList().get(i).equals("0")) {
                File file = new File(upImageBody.getImageList().get(i));
                try {
                    File ompressedImageFile = new Compressor(upImageBody.getContext()).compressToFile(file);
                    RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), ompressedImageFile);
                    MultipartBody.Part body = MultipartBody.Part.createFormData("files", ompressedImageFile.getName(), requestBody);
                    list.add(body);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        JsNetworkService.getInstance().getIJsNetworkService()
                .upImage(list)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UpImageBean>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        Disposable mDisposable; //用于Activity销毁时停止执行
                        mDisposable = d;
                        callBack.onDispose(mDisposable);
                    }

                    @Override
                    public void onNext(@NonNull UpImageBean upImageBean) {

                        callBack.onSuccess(upImageBean);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        callBack.onError("Server Error", "网络异常，请稍后再试");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


}
